package db;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据库对象基类
 * 所有非静态字段只能是对应数据表中的字段
 */
public abstract class Entity implements Serializable {

    private long key_id;

    /**
     * 子类可重写
     */
    public long getId() {
        return key_id;
    }

    public void setId(long key_id) {
        this.key_id = key_id;
    }

    /**
     * 对应的数据表名
     */
    public abstract String tableName();

    /**
     * 插入对象到数据库表中
     */
    public long SaveToDB() {
        Map<String, Object> dbFieldsMap = this.listDBFields();
        if (dbFieldsMap == null || dbFieldsMap.size() == 0) {
            return -1;
        }
        if (this.getId() > 0) {
            dbFieldsMap.put("id", this.getId());
        }
        StringBuilder sql = new StringBuilder("INSERT INTO ");
        sql.append(this.tableName());
        sql.append(" (");
        for (String key : dbFieldsMap.keySet()) {
            sql.append(key).append(",");
        }
        sql.replace(sql.length() - 1, sql.length(), ") VALUES(");
        for (String key : dbFieldsMap.keySet()) {
            sql.append("?,");
        }
        sql.replace(sql.length() - 1, sql.length(), ")");
        return DBQuery.insert(sql.toString(), dbFieldsMap.values().toArray());
    }

    /**
     * 放在CommonDAO里根据id删除还是有点危险了
     * 还是放在这里让对应类对象自己调，防止误调误删
     */
    public long Delete() {
        String sql = "delete from " + tableName() + " where id=?";
        return DBQuery.update(sql, this.getId());
    }

    /**
     * 更新对象对应的一条数据记录
     */
    public long DoUpdate() {
        Map<String, Object> dbFieldsMap = this.listDBFields();
        Object[] params = new Object[dbFieldsMap.size()];
        StringBuilder sql = new StringBuilder("update ").append(tableName()).append(" set ");
        int index = 0;
        for (Map.Entry entry : dbFieldsMap.entrySet()) {
            sql.append(entry.getKey()).append("=?,");
            params[index++] = entry.getValue();
        }
        sql.replace(sql.length() - 1, sql.length(), " where id=");
        sql.append(this.getId());
        return DBQuery.update(sql.toString(), params);
    }

    /**
     * 列出对象中（不包括父类）除id、update_time（此字段自动更新）外所有非静态字段及其字段值，即对应数据表中的字段
     * 因此不允许类中声明额外的非静态字段，以避免混乱
     */
    protected Map<String, Object> listDBFields() {
        Field[] fields = this.getClass().getDeclaredFields();
        List<Field> dbFieldList = new ArrayList<>();
        for (Field field : fields) {
            field.setAccessible(true);
            if (!Modifier.isStatic(field.getModifiers()) && !"id".equals(field.getName()) && !"update_time".equals(field.getName())) {
                dbFieldList.add(field);
            }
        }
        Map<String, Object> dbFieldMap = new HashMap<>();
        try {
            for (Field field : dbFieldList) {
                dbFieldMap.put(field.getName(),field.get(this));
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            return null;
        }
        return dbFieldMap;
    }

}
